package com.yaoxiaowen.project2.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * Created by yaowen on 2016/9/2 with tongshai desktop.
 * qq: 2669932513
 */
public class FileUtil {

    /**
     * 以字符为单位读取文件，常用于读文本，数字等类型的文件
     *
     * http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html
     */
    public  static String readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;

        StringBuilder sb = new StringBuilder();

        try {
            System.out.println("以字符为单位读取文件内容，一次读多个字节：");
            // 一次读多个字符
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // 读入多个字符到字符数组中，charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 同样屏蔽掉\r不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != '\r')) {
//                    System.out.print(tempchars);
                    sb.append(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '\r') {
                            continue;
                        } else {
//                            System.out.print(tempchars[i]);
                            sb.append(tempchars[i]);
                        }
                    }
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        return sb.toString();
    } //end of "readFileByChars()"
}
